package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.ITmcUserService;
import com.ruoyi.system.service.impl.TmcUserServiceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/tmcuser")
public class TmcUserContreoller extends BaseController {
    @Autowired
    private ITmcUserService tmcUserService;

    //    人员信息
    @GetMapping("/list")
    public TableDataInfo List(TmcUser tmcUser) {
        startPage();
        List<TmcUser> list = tmcUserService.queryList(tmcUser);
        return getDataTable(list);
    }


    //单个人员车位信息
    @GetMapping("/StallList")
    public TableDataInfo StallList(TmcUser tmcUser) {
        startPage();
        List<TmcUserStall> list = tmcUserService.queryStallList(tmcUser);
        return getDataTable(list);
    }

    //单个人员车牌信息
    @GetMapping("/CarcodeList")
    public TableDataInfo CarcodeList(TmcUser tmcUser) {
        startPage();
        List<TmcUserCarcode> list = tmcUserService.queryCarcodeList(tmcUser);
        return getDataTable(list);
    }

    //个人天气信息
    @GetMapping("/queryCity")
    public Map queryCity(String CityName) {
        HashMap map = new HashMap();
        map.put("adcode", tmcUserService.SelectCity(CityName));
        return map;
    }


    //疫情人员信息
    @GetMapping("/EpidemicList")
    public TableDataInfo EpidemicList(TmcEpidemicUser tmcEpidemicUser) {
        startPage();
        List<TmcEpidemicUser> list = tmcUserService.queryEpidemicList(tmcEpidemicUser);
        return getDataTable(list);
    }

    //疫情人员出入信息
    @GetMapping("/EpidemicRecordList")
    public TableDataInfo EpidemicRecordList(TmcEpidemicUser tmcEpidemicUser) {
        startPage();
        List<TmcEpidemicUserRecord> list = tmcUserService.queryEpidemicRecordList(tmcEpidemicUser);
        return getDataTable(list);
    }

    //账单
    @GetMapping("/queryFeeListById")
    public TableDataInfo queryFeeListById(TmcHouseSubbill tmcEpidemicUser) {
        startPage();
        List<TmcHouseSubbill> list = tmcUserService.queryFeeListById(tmcEpidemicUser);
        return getDataTable(list);
    }

    //    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/client/list")
    public TableDataInfo list(ClientUser clientUser) {
        startPage();
        List<ClientUser> list = tmcUserService.selectClientUserList(clientUser);
        return getDataTable(list);
    }

    /**
     * 导出【物业人员管理】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @Log(title = "【物业人员管理】", businessType = BusinessType.EXPORT)
    @GetMapping("/client/export")
    public AjaxResult export(ClientUser clientUser) {
        List<ClientUser> list = tmcUserService.selectClientUserList(clientUser);
        ExcelUtil<ClientUser> util = new ExcelUtil<ClientUser>(ClientUser.class);
        return util.exportExcel(list, "user");
    }

    /**
     * 获取【物业人员管理】详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/client/{id}")
    public AjaxResult clientgetInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tmcUserService.selectClientUserById(id));
    }

    /**
     * 新增【物业人员管理】
     */
//    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "【物业人员管理】", businessType = BusinessType.INSERT)
    @PostMapping("/client/add")
    public AjaxResult add(@RequestBody ClientUser clientUser) {
        if (tmcUserService.insertClientUser(clientUser) == 0) {
            return AjaxResult.error("当前员工已存在");
        } else {
            return AjaxResult.success("添加成功");
        }
    }

    /**
     * 修改【物业人员管理】
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "【物业人员管理】", businessType = BusinessType.UPDATE)
    @PutMapping("/client/put")
    public AjaxResult edit(@RequestBody ClientUser clientUser) {
        if (tmcUserService.updateClientUser(clientUser) == 0) {
            return AjaxResult.error("当前员工已存在");
        } else {
            return AjaxResult.success("修改成功");
        }
    }

    //    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/DistrictList")
    public TableDataInfo DistrictList() {
        startPage();
        List<District> list = tmcUserService.selectDistrictList();
        return getDataTable(list);
    }

    /**
     * 删除【物业人员管理】
     */
//    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "【物业人员管理】", businessType = BusinessType.DELETE)
    @DeleteMapping("/client/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tmcUserService.deleteClientUserByIds(ids));
    }

    /**
     * @Description:
     * @Param:
     * @returns:
     * @Author: Administrator
     * @Date: 2021/4/6 15:28
     **/
//      小程序接口
//      尝试登录接口
    @Log(title = "【小程序尝试登录】")
//    @GetMapping("/client/logintype")
//    public TmcUser login(String code) {
//        return new TmcUser();
//    }
    //授权
    @ApiOperation(value = "微信用户授权", notes = "微信用户授权")
    @ApiImplicitParam(name = "WxCode", value = "微信code", required = true, dataType = "String", paramType = "query")
    @ApiResponses({
            @ApiResponse(code = 500, message = "服务器异常"),
            @ApiResponse(code = 200, message = "成功")
    })
    @GetMapping("/client/logintype")
    @ResponseBody
    public AjaxResult loginwechart(@RequestParam(value = "code") String code) {
        //@RequestParam(value = "WxCode") String WxCode
        //请求微信api获取用户的openid和sessionKey
        //   JSONObject jsonObject = getUserWXLoginInfo(loginDto.getWxCode());
        System.out.println(code);
        JSONObject jsonObject = null;
        String openid = "";
        try {
            jsonObject = getUserWXLoginInfo(code);
            openid = (String) jsonObject.get("openid");
            String sessionKey = (String) jsonObject.get("session_key");
//           拿到唯一openid

        } catch (Exception e) {
            return AjaxResult.error("服务器错误", jsonObject);
        }
        //保存到数据库
        TmcUser user = new TmcUser();
        user.setOpenid(openid);
        if (tmcUserService.qureyopenIDsum(openid) <= 0) {
            tmcUserService.insertTmcUser(user);
        }
        List<TmcUser> tmcUsers = tmcUserService.queryList(user);
        return AjaxResult.success("成功", tmcUsers.get(0));
    }

    private JSONObject getUserWXLoginInfo(String WxCode) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        String parem = "appid=wxd8675e585c95ea0e&secret=7b3f5e6527ee3ec5fb850846b154820d&js_code=" + WxCode + "&grant_type=authorization_code";
        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(HttpUtils.sendPost(requestUrl, parem));
        return jsonObject;
    }

    @Autowired
    private RedisCache redisCache;

    //      短信发送
    @Log(title = "【短信验证码】")
    @GetMapping("/client/phone")
    public Map Phone(String phone) {
        System.out.println("进入方法---------------------------------");
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "LTAI4G9ZRUFwAw7p7q8FRRxe", "U9K3WEEZ3h1UY9mxr3cUJmfgu7tWpx");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-beijing");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "天目智慧社区");
        request.putQueryParameter("TemplateCode", "SMS_181852874");
        final String Code = String.format("%04d", new Random().nextInt(9999));
        redisCache.setCacheObject("captcha_codes", Code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + Code + "\"}");
        System.out.println("code:" + Code);
        System.out.println("---------------------------------");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println("11111111111111111111111");
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
            System.out.println("异常");
        }
        HashMap map1 = new HashMap();
        map1.put("ID", Code);
        map1.put("Status", 22);
        map1.put("ErrorMessage", "验证码发送成功");
        System.out.println(map1.toString());
        return map1;
    }

    //      绑定用户
    @Log(title = "【用户绑定】")
    @PostMapping("/App/BindUserInfo")
    public Map BindUserInfo(@RequestBody Map map) {
        TmcUser tmcUser = new TmcUser();
        tmcUser.setCellphone((String) map.get("CellPhone"));
        tmcUser.setUsername((String) map.get("UserName"));
        tmcUser.setOpenid((String) map.get("OpenID"));
        tmcUser.setAvatarurl((String) map.get("AvatarUrl"));
        String captchaCode = (String) map.get("VCode");
        if (tmcUserService.qureyPhonesum((String) map.get("CellPhone")) <= 0) {
            tmcUserService.insertTmcUser(tmcUser);
        }
        HashMap map1 = new HashMap();
        map1.put("ID", tmcUser.getPublicuserId());
        map1.put("Status", 22);
        try {
            if (captchaCode == null) {
                map1.put("ErrorMessage", "注册失败");
                return map1;
            }
            String captchaValue = redisCache.getCacheObject("captcha_codes");
            if (captchaValue == null) {
                map1.put("ErrorMessage", "注册失败");
                return map1;
            }
            redisCache.deleteObject(captchaCode);
            if (captchaValue.compareTo(captchaCode) != 0) {
                map1.put("ErrorMessage", "注册失败");
                return map1;
            }
            map1.put("ErrorMessage", "注册成功");
            return map1;
        } catch (Exception e) {
            map1.put("ErrorMessage", "注册失败");
            return map1;
        }
    }
    //用户app
    //     提交用户表单
    @Log(title = "【提交用户表单】")
    @PostMapping("/app/Login")
    public TmcUser Login(@RequestParam() HashMap map) {
        System.out.println(map);
        TmcUser tmcUser = new TmcUser();
        tmcUser.setCellphone((String) map.get("CellPhone"));
        tmcUser.setUsername((String) map.get("UserName"));
        tmcUser.setOpenid((String) map.get("OpenID"));
        tmcUser.setAvatarurl((String) map.get("AvatarUrl"));
        if (tmcUserService.qureyPhonesum((String) map.get("CellPhone")) ==1) {
            return tmcUserService.queryUser(tmcUser);
        }
        return null;
    }
    //      绑定用户
    @Log(title = "【用户注册】")
    @PostMapping("/client/BindUserInfo")
    public Map AppBindUserInfo(@RequestBody Map map) {

        TmcUser tmcUser = new TmcUser();
        tmcUser.setCellphone((String) map.get("CellPhone"));
        tmcUser.setUsername((String) map.get("UserName"));
        tmcUser.setOpenid((String) map.get("OpenID"));
        String captchaCode = (String) map.get("VCode");
        HashMap map1 = new HashMap();
        map1.put("ID", tmcUser.getPublicuserId());
        map1.put("Status", 22);
        try {
            if (captchaCode == null) {
                map1.put("ErrorMessage", "登录失败");
                return map1;
            }
            String captchaValue = redisCache.getCacheObject("captcha_codes");
            if (captchaValue == null) {
                map1.put("ErrorMessage", "登录失败");
                return map1;
            }
            redisCache.deleteObject(captchaCode);
            if (captchaValue.compareTo(captchaCode) != 0) {
                map1.put("ErrorMessage", "登录失败");
                return map1;
            }
            tmcUserService.updateTmcUser(tmcUser);
            map1.put("ErrorMessage", "登录成功");
            return map1;
        } catch (Exception e) {
            map1.put("ErrorMessage", "登录失败");
            return map1;
        }
    }
    //      根据id查用户信息
    @Log(title = "【根据id查用户信息】")
    @GetMapping("/client/BindUserInfoById")
    public AjaxResult BindUserInfoById(@Param("publicUserID") Long publicUserID) {
        TmcUser tmcUser = new TmcUser();
        tmcUser.setPublicuserId(publicUserID);
        tmcUser = tmcUserService.queryListById(tmcUser.getPublicuserId());
        if (null != tmcUser) {
            return AjaxResult.success("登陆成功", tmcUser);
        } else return AjaxResult.error("登陆失败,用户不存在");
    }
    //      根据id查房产信息

    //      根据id查车辆车位信息
    @Log(title = "【根据id查车辆车位信息】")
    @GetMapping("/client/QueryUserParkingCarInfo")
    public AjaxResult QueryUserParkingCarInfo(@Param("publicUserID") Long publicUserID) {
        TmcUser tmcUser = new TmcUser();
        tmcUser.setPublicuserId(publicUserID);
        HashMap map = tmcUserService.QueryUserParkingCarInfo(tmcUser);
        return AjaxResult.success(map);
    }
//     编辑车辆信息

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tmcUserService.selectTmcUserCarById(id));
    }

    /**
     * 修改【車牌】
     */
    @Log(title = "【車牌】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TmcUserCarcode tmcUserCarcode) {
        return toAjax(tmcUserService.updateTmcUserCar(tmcUserCarcode));
    }

    @Log(title = "【添加车牌】", businessType = BusinessType.INSERT)
    @PostMapping("/car/add")
    public Map add(@RequestBody Map map) {
        if ((Integer) map.get("ID") == 0) {
            TmcUserCarcode tmcUserCar = new TmcUserCarcode();
            tmcUserCar.setPublicuserId(Long.valueOf(map.get("PublicUser_ID") + ""));
            tmcUserCar.setCarnum(map.get("CarNum") + "");
            tmcUserService.insertTmcUserCar(tmcUserCar);
            HashMap map1 = new HashMap();
            map1.put("ID", tmcUserCar.getCarId());
            map1.put("Status", 22);
            map1.put("ErrorMessage", "新增车辆成功");
            return map1;
        } else {
            TmcUserCarcode tmcUserCar = new TmcUserCarcode();
            tmcUserCar.setCarId((Long) map.get("ID"));
            tmcUserCar.setPublicuserId(Long.valueOf(map.get("PublicUser_ID") + ""));
            tmcUserCar.setCarnum((String) map.get("CarNum") + "");
            tmcUserService.updateTmcUserCar(tmcUserCar);
            HashMap map1 = new HashMap();
            map1.put("ID", tmcUserCar.getCarId());
            map1.put("Status", 22);
            map1.put("ErrorMessage", "修改车辆成功");
            return map1;
        }

    }

    /**
     * 删除【車牌】
     */
    @Log(title = "【車牌】", businessType = BusinessType.DELETE)
    @DeleteMapping("/car")
    public HashMap carremove(Long id) {
        HashMap map1 = new HashMap();
        map1.put("ID", id);
        map1.put("Status", 0);
        if (tmcUserService.deleteTmcUserCarById(id) == 1) {
            map1.put("ErrorMessage", "删除成功");
        } else {
            map1.put("ErrorMessage", "删除失败");
        }


        return map1;
    }
//     删除车辆信息

//     根据房产和用户id查询小天

    //     提交用户表单
    @Log(title = "【提交用户表单】")
    @GetMapping("/client/CommitUserFormId")
    public AjaxResult CommitUserFormId(@RequestBody HashMap map) {
        TmcUserFormid tmcUserFormid = new TmcUserFormid();
        tmcUserFormid.setFormid((String) map.get("FormId"));
        tmcUserFormid.setFormtype((Integer) map.get("FormType"));
        tmcUserFormid.setPublicuserId((Integer) map.get("PublicUser_ID"));
        int i = tmcUserService.insertTmcUserFormid(tmcUserFormid);
        if (i != 1) {
            return AjaxResult.error("失败");
        } else {
            return AjaxResult.success("成功");
        }
    }

    //    app定账绑号
    @PostMapping("/UpdateUser")
    public void setUser(@RequestParam() HashMap map) {

        return;
    }
}
